<template>
  <view class="app">
    <view class="top-bg">
      <image class="top-img" mode="widthFix" src="/static/image/mine/bg.jpg"> </image>
    </view>
    <view class="login-box">
      <!-- 头像 -->
      <view class="avatar-overlay">
        <view class="avatar-box">
          <view class="avatar-btn" v-if="!fansStore.fansinfo.token">
            <image class="avatar" :src="config.custom.avatar" />
          </view>
          <button class="avatar-btn" v-else @click="nav.jump('/pages/setting/info')">
            <image
              class="avatar"
              :src="avatar || config.custom.avatar"
              @error="avatar = config.custom.avatar"
            ></image>
          </button>
        </view>
      </view>

      <!-- 登录按钮 -->
      <button
        v-if="!fansStore.fansinfo.token"
        class="login-btn btn-view"
        @click="nav.jump('/pages/auth/login')"
      >
        登录/注册
      </button>
      <view class="flex flex-col ml-20rpx" v-else>
        <text class="account-nickname">{{ fansStore.fansinfo.nickname || config.custom.nickname }}</text>
        <view class="flex items-center">
          <image src="@/static/image/mine/lv.png" mode="widthFix" class="w-30rpx" />
          <text class="ml-10rpx mr-15rpx color-white">{{ fansStore.fansinfo.level_name }}</text>
          <view class="invite-code" @click="copyInviteCode()">
            邀请码 {{ fansStore.fansinfo.invite_code }}
          </view>
        </view>
      </view>
    </view>

    <!-- 资产 -->
    <view class="assets-box">
      <view class="assets-header" @click="nav.jump('/pages/goods/gift')">
        <view class="flex items-center">
          <view class="header-title">一键成为会员，尽享专属好礼</view>
          <view class="btn-right">
            <u-icon name="arrow-right" custom-prefix="mt-icon" size="20" color="#8b7542"></u-icon>
          </view>
        </view>
      </view>
      <view class="assets-num">
        <view class="assets-num-item" @click="nav.jump('/pages/rebate/index')">
          <text>{{ assetsStore.rebate_money }}</text>
          <view class="mt-3rpx font-size-26rpx">奖励</view>
        </view>
        <view class="assets-num-item">
          <text>{{ assetsStore.withdraw_money }}</text>
          <view class="mt-3rpx font-size-26rpx">提现</view>
        </view>
        <view class="assets-num-item">
          <text>{{ assetsStore.left_integral }}</text>
          <view class="mt-3rpx font-size-26rpx">积分</view>
        </view>
      </view>
    </view>

    <!-- 邀请码 -->
    <view class="member-code" @click="nav.jump('/pages/mine/qrcode')">
      <u-icon name="qrcode" custom-prefix="mt-icon" size="30" color="white"></u-icon>
      <text class="color-white pl-1 font-size-28rpx">邀请码</text>
    </view>

    <!-- 头像、昵称补充 -->
    <u-popup v-model="showWin" mode="bottom" border-radius="30" height="46vh" :mask-close-able="false">
      <view class="drawer-box">
        <view class="company-info">
          <view class="flex items-center">
            <view class="company-logo">
              <image mode="widthFix" :src="config.custom.loading_logo" />
            </view>
            <text class="ml-10rpx font-size-28rpx font-600">{{ config.custom.company_anme }}</text>
          </view>
          <view class="flex flex-col mt-30rpx">
            <text class="tips-text">获取您的昵称、头像</text>
          </view>

          <view class="close-btn" @click="showWin = false">
            <u-icon custom-prefix="mt-icon" name="close-bold" color="black" size="20"></u-icon>
          </view>
        </view>

        <view class="account-info">
          <view class="form-item">
            <text class="form-label">头像</text>
            <button class="btn-view avatar-choose" open-type="chooseAvatar" @chooseavatar="getAvatar">
              <image class="user-avatar" :src="form.avatar || config.custom.avatar"></image>
              <u-icon size="24" color="#b7b7b7" name="arrow-right"></u-icon>
            </button>
          </view>
          <view class="form-item">
            <text class="form-label">昵称</text>
            <input
              type="nickname"
              :cursor-spacing="25"
              placeholder="请填写昵称"
              placeholder-class="input-placeholder"
              v-model="form.nickname"
              @change="getNickname"
            />
          </view>
        </view>

        <view class="submit-box">
          <text class="save-btn" @click="saveAccount">保 存</text>
        </view>
      </view>
    </u-popup>

    <view>
      <image class="w-full" mode="widthFix" src="/static/image/mine/welfare.jpg" />
    </view>

    <!-- 导航 -->
    <order-nav />
    <service-nav />
    <tool-nav />

    <!-- 版权 -->
    <view class="copyright">
      <text>©技术支持：</text>
      <text selectable>anma121(wx)</text>
    </view>
  </view>
</template>

<script lang="ts" setup>
  import OrderNav from './order.vue';
  import ServiceNav from './service.vue';
  import ToolNav from './tool.vue';
  import { useFansStore } from '@/store/fans';
  import { useAssetsStore } from '@/store/assets';
  import { ref, reactive } from 'vue';
  import { setFans } from '@/api/fans/index';
  import { msg } from '@/utils/msg';
  import { config } from '@/config/env';
  import { onShow } from '@dcloudio/uni-app';
  import { uploadImgToServerByWeixin } from '@/common/upload';
  import { report } from '@/utils/exception';
  import { nav } from '@/utils/homer';
  import { cache } from '@/utils/cache';
  import { getFansInfo } from '@/api/fans';
  import { getMemberInfo, getMemberAssetsInfo } from '@/api/member';
  import { watchTask, delTask } from '@/api/task';

  const fansStore = useFansStore();
  const assetsStore = useAssetsStore();
  const showWin = ref<boolean>(false);
  const avatar = ref<string>(fansStore.fansinfo.avatar);
  const form = reactive({
    avatar: '',
    nickname: '',
  });
  let resetAvatar = false;

  const copyInviteCode = () => {
    return;
    uni.setClipboardData({
      data: fansStore.fansinfo.invite_code,
      success: () => {
        msg.text('邀请码复制成功');
      },
    });
  };

  const openAccount = () => {
    form.avatar = fansStore.fansinfo.avatar;
    form.nickname = fansStore.fansinfo.nickname;
    showWin.value = true;
  };

  // 同步用户信息
  const syncFansInfoTask = (taskId: number) => {
    getFansInfo()
      .then((res) => {
        fansStore.fansinfo.avatar = res.data.avatar;
        fansStore.fansinfo.nickname = res.data.nickname;
        fansStore.fansinfo.username = res.data.username;
        fansStore.fansinfo.phone = res.data.phone;
        delTask(taskId);
      })
      .catch((err) => {
        report(err);
      });
  };

  // 同步会员信息
  const syncMemberInfoTask = (taskId: number) => {
    getMemberInfo()
      .then((res) => {
        fansStore.fansinfo.level_name = res.data.level_name;
        delTask(taskId);
      })
      .catch((err) => {
        report(err);
      });
  };

  // 同步会员信息
  const syncMemberAssetsInfoTask = (taskId: number) => {
    getMemberAssetsInfo()
      .then((res) => {
        assetsStore.recharge_money = res.data.recharge_money;
        assetsStore.rebate_money = res.data.rebate_money;
        assetsStore.withdraw_money = res.data.withdraw_money;
        assetsStore.frozen_money = res.data.frozen_money;
        assetsStore.left_integral = res.data.left_integral;
        assetsStore.total_integral = res.data.total_integral;
        delTask(taskId);
      })
      .catch((err) => {
        report(err);
      });
  };

  const daemon = () => {
    if (cache.get('task_cache')) return;

    watchTask()
      .then((res) => {
        cache.set('task_cache', 1, '10s');

        res.data.list.forEach((task: any) => {
          switch (task.action) {
            case 'update_assets_info':
              syncMemberAssetsInfoTask(task.id);
              break;
            case 'update_member_info':
              syncMemberInfoTask(task.id);
              break;
            case 'update_fans_info':
              syncFansInfoTask(task.id);
              break;
          }
        });
      })
      .catch((err) => {
        report(err);
      });
  };

  onShow(() => {
    if (fansStore.fansinfo.token) {
      if (!fansStore.fansinfo.avatar || !fansStore.fansinfo.nickname) {
        setTimeout(() => {
          openAccount();
        }, 600);
      }

      // @todo 守护进程待写
      // daemon();
    }
  });

  const getAvatar = (e: any) => {
    resetAvatar = true;
    form.avatar = e.detail.avatarUrl;
  };

  const getNickname = (e: any) => {
    form.nickname = e.detail.value;
  };

  const saveAccount = () => {
    if (form.avatar == '') {
      return msg.error('请上传头像');
    }
    if (form.nickname == '') {
      return msg.error('请填写昵称');
    }

    if (resetAvatar) {
      // 变更头像，需要上传服务器
      const fileName = form.avatar.substring(form.avatar.lastIndexOf('/') + 1);
      uploadImgToServerByWeixin(form.avatar, fileName)
        .then((res: any) => {
          setFans({ avatar: res, nickname: form.nickname })
            .then(() => {
              resetAvatar = false;
              form.avatar = res;
              fansStore.fansinfo.avatar = form.avatar;
              fansStore.fansinfo.nickname = form.nickname;
              fansStore.invite_poster = '';
              msg.success('昵称、头像上传成功', 2000, () => (showWin.value = false));
            })
            .catch((err) => {
              report(err);
            });
        })
        .catch((err) => {
          msg.error(err);
        });
    } else {
      // 头像未变更
      setFans({ nickname: form.nickname })
        .then((res) => {
          fansStore.fansinfo.nickname = form.nickname;
          fansStore.invite_poster = '';
          msg.success('昵称、头像上传成功', 2000, () => (showWin.value = false));
        })
        .catch((err) => {
          report(err);
        });
    }
  };
</script>

<style lang="scss" scoped>
  .top-bg {
    height: 490rpx;
    .top-img {
      position: relative;
      width: 100%;
    }
  }

  .login-box {
    display: flex;
    flex-direction: row;
    align-items: center;
    position: absolute;
    top: 60rpx;
    left: 50rpx;

    .avatar-overlay {
      display: flex;
      flex-direction: column;
      width: 100rpx;
      height: 100rpx;
      background: white;
      border-radius: 50%;
      align-items: center;
      justify-content: center;

      .avatar-box {
        position: relative;
        border-radius: 50%;
        overflow: hidden;
        width: 90rpx;
        height: 90rpx;

        .avatar-btn {
          display: contents;
          width: 90rpx;
          height: 90rpx;

          .avatar {
            width: 90rpx;
            height: 90rpx;
          }
        }
      }
    }

    .login-btn {
      font-size: 30rpx;
      padding-left: 20rpx;
      color: white;
      letter-spacing: 2rpx;
    }

    .invite-code {
      font-size: 24rpx;
      background: white;
      color: #024341;
      border-radius: 20rpx;
      padding: 6rpx 20rpx;
    }
  }

  .assets-box {
    position: absolute;
    top: 245rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100%;

    .assets-header {
      width: 82%;
      height: 90rpx;
      display: flex;
      align-items: center;
      justify-content: flex-end;
      padding: 0 45rpx;
      border-top-left-radius: 20rpx;
      border-top-right-radius: 20rpx;
      background: linear-gradient(to right, #cbaf71, #85703f);

      .header-title {
        color: #fff;
        font-size: 22rpx;
        opacity: 0.8;
      }

      .btn-right {
        display: flex;
        align-items: center;
        justify-content: center;
        padding-left: 3rpx;
        width: 35rpx;
        height: 35rpx;
        border-radius: 50%;
        margin-left: 15rpx;
        background: #fff;
      }
    }

    .assets-num {
      display: flex;
      align-items: center;
      width: 92%;
      background: #fff;
      border-radius: 12rpx;
      height: 135rpx;

      .assets-num-item {
        display: flex;
        flex: 1;
        flex-direction: column;
        align-items: center;

        &:not(:last-child) {
          border-right: 1rpx solid #c6c4c4;
        }
      }
    }
  }

  .member-code {
    position: absolute;
    top: 50rpx;
    right: 50rpx;
  }

  .account-nickname {
    color: #ffffff;
    font-size: 30rpx;
    font-weight: 600;
    padding-bottom: 8rpx;
  }

  .drawer-box {
    height: 100%;
    padding: 30rpx 50rpx;

    .company-info {
      margin-bottom: 30rpx;
      padding-bottom: 20rpx;

      .company-logo {
        width: 60rpx;
        height: 60rpx;
        border-radius: 50%;
        overflow: hidden;

        image {
          width: 100%;
        }
      }

      .tips-text {
        // color: #a5a5a5;
        font-size: 30rpx;
      }

      .close-btn {
        position: absolute;
        top: 32rpx;
        right: 32rpx;
        padding: 15rpx;
        display: flex;
        border-radius: 50%;
        background: #ebebeb;
      }
    }

    .account-info {
      .form-item {
        display: flex;
        align-items: center;
        border-bottom: 1px solid #f5f5f5;
        height: 120rpx;

        .form-label {
          width: 80rpx;
          font-size: 30rpx;
        }

        input {
          font-size: 30rpx;
          padding: 0 20rpx;
          flex: 1;
        }

        .avatar-choose {
          display: flex;
          align-items: center;
          justify-content: space-between;
          flex: 1;
          padding-left: 20rpx;

          .user-avatar {
            width: 80rpx;
            height: 80rpx;
            border-radius: 50%;
          }
        }
      }
    }

    .submit-box {
      display: flex;
      flex-direction: column;
      padding: 40rpx 0 10rpx;

      .save-btn {
        width: 100%;
        font-size: 28rpx;
        font-weight: 600;
        padding: 25rpx 0;
        border-radius: 50rpx;
        text-align: center;
        color: white;
        background-image: linear-gradient(to right, #f3204f, #f33720);
        box-shadow: rgba(255, 28, 0, 0.2) 0 5rpx 12rpx;
      }
    }
  }

  .copyright {
    display: flex;
    justify-content: center;
    margin: 80rpx 0 30rpx;
    font-size: 24rpx;
    color: #b8b8b8;
  }
</style>
